package com.demo.service.controller;

import com.demo.service.config.MqttClientConnection;
import com.demo.service.properties.MqttProperties;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试发布主题Controller
 */
@RestController
@RequestMapping("/mqtt")
public class MqttController {

    //连接配置
    @Autowired
    private MqttConnectOptions ConnectOptions;

    //客户端连接
    @Autowired
    private MqttClientConnection mqttClientConnection;

    //Mqtt配置
    @Autowired
    private MqttProperties mqttProperties;


    /**
     * 发布主题
     *
     * @param message
     * @return
     */
    @PostMapping("/publish")
    public String publishMessage(@RequestBody String message) {
        String response;
        try {
            //获取连接对象
            MqttClient publishClient = mqttClientConnection.getPublishClient();
            //将连接配置传参并连接
            publishClient.connect(ConnectOptions);
            //发布主题
            publishClient.publish(mqttProperties.getTopic(), message.getBytes(), mqttProperties.getQos(), false);
            //销毁连接
            publishClient.disconnect();
            response = "Message published successfully!";
        } catch (MqttException e) {
            response = "Failed to publish message: " + e.getMessage();
        }
        return response;
    }
}